package org.shangrila.bme.mb;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.enterprise.context.SessionScoped;
import javax.faces.model.SelectItem;
import javax.inject.Inject;
import javax.inject.Named;

import org.primefaces.event.RowEditEvent;
import org.shangrila.app.sys.cfg.AppInitInfo;
import org.shangrila.app.sys.shiro.SecUtil;
import org.shangrila.app.wfm.mb.WfmTaskMgrMB;
import org.shangrila.bme.eo.AppFileInfo;
import org.shangrila.bme.eo.BmeAcception;
import org.shangrila.bme.eo.BmeAcceptionDetail;
import org.shangrila.bme.eo.BmeContract;
import org.shangrila.bme.eo.BmeSaleout;
import org.shangrila.bme.eo.BmeSaleoutDetail;
import org.shangrila.bme.eo.BmeSupplier;
import org.shangrila.bme.eo.BmeWfmService;
import org.shangrila.comm.dao.DbAccess;
import org.shangrila.comm.helper.IDHelper;
import org.shangrila.wfm.core.WfmEngine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Named
@SessionScoped
public class AcceptionMB implements Serializable {
	private static final long serialVersionUID = -513126664217112L;
	private final Logger log = LoggerFactory.getLogger(this.getClass());

    private BmeAcception io = new BmeAcception();//录入    

	private List<BmeAcceptionDetail> vod = new ArrayList<BmeAcceptionDetail>(); //详情
	private BmeAcceptionDetail selectedd = new BmeAcceptionDetail();//录入以及选择详情信息	

	private List<BmeContract> bmeContracts; 	
	private BmeContract selectedContract = new BmeContract(); 

	private List<BmeSaleoutDetail> bmeSaleoutDetails = new ArrayList<BmeSaleoutDetail>();
	private BmeSaleoutDetail selectedSaleoutDetail = new BmeSaleoutDetail(); 
	private List<BmeSaleoutDetail> selectedSaleoutDetails = new ArrayList<BmeSaleoutDetail>();

	private List<BmeSupplier> bmeSuppliers; 	
	private BmeSupplier selectedSupplier = new BmeSupplier(); 

	//获取相关数据字典
	private List<SelectItem> itemsStatus = AppInitInfo.getDropdownList("AcceptionStatus"); 

	private String operator;	
	private String uploadedFile="";
	private String uploadedFileImage="";

	//附件上传页面参数传递
	private String uploadForType="5";
	private String uploadForId="0";
	private String uploadForName="0";
	
	private String processName="wf_ysdsh";

	@Inject
	private DbAccess db;
	@Inject
	BmeCommEntityService bmeCommEntityService; 
	@Inject
	private AttachUploadMB attachUploadMB;
	
	@PostConstruct
    public void init() {
		log.info("@PostConstruct..."+this.getClass());		
		try{
			operator = SecUtil.getCachedShiroUser().getUserno();
		}
		catch(Exception ex){
			operator="bme";
		}
		newIo();
    }

	public void initdata() {
		bmeContracts = bmeCommEntityService.getBmeContracts();
		setBmeSuppliers(bmeCommEntityService.getBmeSuppliers());
	}
	
	//接收WFM参数
	public void initwfm() {
		WfmTaskMgrMB wfmTaskMgrMB = (WfmTaskMgrMB)AppInitInfo.findSessionBeanByName("wfmTaskMgrMB");
		if(null != wfmTaskMgrMB) {
			String businessId = wfmTaskMgrMB.getSelectedTask().getServiceNo();
			log.info("initwfm-purch="+businessId);
			String sql = "SELECT m FROM BmeAcception m where m.id=?1";	
			List<BmeAcception> ls = db.findBySql(sql,new Object[]{businessId});
			if(ls.size()>0) {
				io = ls .get(0);	
				vod = io.getBmeAcceptionDetails();
				selectedContract = io.getBmeContract();
				for(BmeSupplier sp:bmeSuppliers) {
					if(sp.getId().equals(io.getSupplierId())) {
						selectedSupplier = sp;
						break;
					}
				}				
				
			}			
		}
	}
	
    public void newIo() {
    	initdata();
    	io = new BmeAcception();
    	io.setId(IDHelper.genStrID(20));
    	io.setStatus("1");
    	vod = new ArrayList<BmeAcceptionDetail>();
    	attachUploadMB.setVoList(new ArrayList<AppFileInfo>());
    	attachUploadMB.setUploadedFileImage("");
    }    

	//null
	public String nullAction() {
		return null;
	}
    
	//新增
    public void onAdd() {   
    	newIo();
    	AppInitInfo.showMessage("新增验收单", "处理成功");
    }
    //保存
	public String saveAction() {		
		db.beginTransaction();
		io.setBmeContract(selectedContract);
		io.setContName(selectedContract.getName());
		io.setSupplierId(selectedSupplier.getId());
		io.setAddress(selectedContract.getShippingAddress());
		io.setCreateTime(new Date());
		io.setOperator(operator);
		db.insert(io);
		db.commitTransaction();
		
		AppInitInfo.showMessage("单据录入", "处理成功");
		uploadForId=io.getId();
		uploadForName=io.getContName();
		return null;
	}
	
	//提交流程
	public String wfmAction() {
		if(!validDetailAction()) {
			return null;
		}
		//1=制单状态才能提交
		if(null==io.getId() || !"1".equals(io.getStatus())) {
			AppInitInfo.showMessage("warn","提交流程失败", "单据编号为空或者状态不正确");
			return null;
		}
		//提交流程
		//流程参数
		Map<String, Object> args = new HashMap<String, Object>();	
		//业务编号作为WFM实例的serviceNo
		args.put(AppInitInfo.APP_BUSINESS_NO, io.getId());  	
		//下一个流程节点处理工号，all可以代表所有操作工号，只要有此流程角色即可
		args.put(AppInitInfo.APP_OPERATOR,operator);			
		args.put(AppInitInfo.APP_BUSINESS_TYPE, uploadForType);		   //自定义业务参数：业务类型
		//operator="bme";  					   //发起本流程任务操作的工号

		WfmEngine engine = new WfmEngine();//流程引擎
		//启动流程实例
		engine.startService(engine.getWfmdao().findProcessByName(processName).get(0), operator, args);
		
		//填写业务流程日志信息
		BmeWfmService bws = new BmeWfmService();
		bws.setId(IDHelper.genStrID(24));
		bws.setBusinessId(io.getId());
		bws.setBusinessType(uploadForType);
		bws.setCreateTime(new Date());
		bws.setOperator(operator);
		bws.setProcessName(processName);
		bws.setServiceNo(io.getId()); //业务编号作为WFM实例的serviceNo
		io.setStatus("2"); //审核中
		db.begin();
		db.insert(bws);
		db.update(io);
		db.commit();
		AppInitInfo.showMessage("提交流程", "处理成功");
		return null;

	}

	//选择合同
	public void onSelectedContract() {
		if(null!=selectedContract) {
	    	for(BmeSupplier bs : bmeSuppliers) {
	    		if(bs.getId().endsWith(selectedContract.getSupplierId())) {
	    			selectedSupplier = bs;
	    			break;
	    		}
	    	}
			bmeSaleoutDetails = new ArrayList<BmeSaleoutDetail>();
	    	for(BmeSaleout bsd:selectedContract.getBmeSaleouts()) {
	    		bmeSaleoutDetails.addAll(bsd.getBmeSaleoutDetails());
	    	}
	    	io.setAddress(selectedContract.getShippingAddress());
		}
	}
	//验证详单操作的有效性
	public boolean validDetailAction(){
		if(null==io.getCreateTime()) {
			AppInitInfo.showMessage("warn","操作无效", "请确保单据主体信息已经保存");
			return false;
		}
		else
			return true;
	}
    //保存
	public String saveDetail() {
		if(!validDetailAction()) {
			return null;
		}
		List<BmeAcceptionDetail> bpdList = new ArrayList<BmeAcceptionDetail>();
		for(BmeSaleoutDetail bsd:selectedSaleoutDetails) {
			selectedd = new BmeAcceptionDetail();
			selectedd.setId(IDHelper.genStrID(20));
	     	selectedd.setBmeMaterial(bsd.getBmeMaterial());
	     	selectedd.setMdesc(bsd.getBmeMaterial().getMdesc());
	     	selectedd.setMunit(bsd.getBmeMaterial().getMunit());
	     	selectedd.setMquantity(bsd.getMquantity());
	     	selectedd.setMprice(bsd.getMprice());
	     	selectedd.setAmount(bsd.getAmount());
	     	
	     	selectedd.setSpeci(bsd.getSpeci());
	     	selectedd.setProcessQuantity(bsd.getProcessQuantity());
	     	selectedd.setProcessSpeci(bsd.getProcessSpeci());
	     	selectedd.setProcessTeck(bsd.getProcessTeck());
	     	
			selectedd.setBmeAcception(io);
			selectedd.setCreateTime(new Date());
			selectedd.setOperator(operator);
			bpdList.add(selectedd);
		}    		
		try {			
			db.beginTransaction();
			for(BmeAcceptionDetail bcp:bpdList) {
				db.insert(bcp);
			}
			db.commitTransaction();
			vod.addAll(bpdList);
			io.setBmeAcceptionDetails(vod);
			AppInitInfo.showMessage("新增详情录入", "处理成功");
			selectedSaleoutDetails = null;
		}catch(Exception e) {			
			AppInitInfo.showMessage("error","新增详情失败", "请确保单据主体信息已经保存");
			log.error(e.getLocalizedMessage());
			try {
				db.rollbackTransaction();
			}catch(Exception ex) {	}
		}		
		return null;
	}
	//删除
    public String delDetail() {
    	vod.remove(selectedd);
		db.beginTransaction();
		db.delete(selectedd);
		db.commitTransaction();
		
        AppInitInfo.showMessage("删除记录", "处理成功");
        return null;
    }
	
	//编辑
    public void onRowEdit(RowEditEvent event) {
    	selectedd = vod.get(vod.indexOf((BmeAcceptionDetail) event.getObject()));
     	selectedd.setAmount( (null==selectedd.getMprice() ? new BigDecimal(0) : selectedd.getMprice()).multiply((null==selectedd.getMquantity() ? new BigDecimal(0) : selectedd.getMquantity())) );
    	io.setAmount(calculateAmount());
    	db.beginTransaction();
    	db.update(selectedd);
    	db.commitTransaction();
    	AppInitInfo.showMessage("详单修改", "处理成功");
    }
    
    public void onRowCancel(RowEditEvent event) {
    	//AppInitInfo.showMessage("取消修改", "处理成功");
    }
    
    //计算金额字段
    public BigDecimal calculateAmount() {
    	BigDecimal bd = new BigDecimal(0);
    	for(BmeAcceptionDetail bse:vod) {    		
    		bd = bd.add(bse.getAmount());    		
    	}
    	return bd;
    }
    
	public BmeAcception getIo() {
		return io;
	}

	public void setIo(BmeAcception io) {
		this.io = io;
	}

	public List<BmeAcceptionDetail> getVod() {
		return vod;
	}

	public void setVod(List<BmeAcceptionDetail> vod) {
		this.vod = vod;
	}

	public BmeAcceptionDetail getSelectedd() {
		return selectedd;
	}

	public void setSelectedd(BmeAcceptionDetail selectedd) {
		this.selectedd = selectedd;
	}

	public String getUploadedFile() {
		return uploadedFile;
	}

	public void setUploadedFile(String uploadedFile) {
		this.uploadedFile = uploadedFile;
	}

	public String getUploadedFileImage() {
		return uploadedFileImage;
	}

	public void setUploadedFileImage(String uploadedFileImage) {
		this.uploadedFileImage = uploadedFileImage;
	}

	public BmeContract getSelectedContract() {
		return selectedContract;
	}

	public void setSelectedContract(BmeContract selectedContract) {
		this.selectedContract = selectedContract;
	}

	public List<BmeContract> getBmeContracts() {
		return bmeContracts;
	}

	public void setBmeContracts(List<BmeContract> bmeContracts) {
		this.bmeContracts = bmeContracts;
	}

	public String getUploadForType() {
		return uploadForType;
	}

	public void setUploadForType(String uploadForType) {
		this.uploadForType = uploadForType;
	}

	public String getUploadForId() {
		return uploadForId;
	}

	public void setUploadForId(String uploadForId) {
		this.uploadForId = uploadForId;
	}

	public String getUploadForName() {
		return uploadForName;
	}

	public void setUploadForName(String uploadForName) {
		this.uploadForName = uploadForName;
	}

	public List<BmeSaleoutDetail> getBmeSaleoutDetails() {
		return bmeSaleoutDetails;
	}

	public void setBmeSaleoutDetails(List<BmeSaleoutDetail> bmeSaleoutDetails) {
		this.bmeSaleoutDetails = bmeSaleoutDetails;
	}

	public BmeSaleoutDetail getSelectedSaleoutDetail() {
		return selectedSaleoutDetail;
	}

	public void setSelectedSaleoutDetail(BmeSaleoutDetail selectedSaleoutDetail) {
		this.selectedSaleoutDetail = selectedSaleoutDetail;
	}

	public List<BmeSupplier> getBmeSuppliers() {
		return bmeSuppliers;
	}

	public void setBmeSuppliers(List<BmeSupplier> bmeSuppliers) {
		this.bmeSuppliers = bmeSuppliers;
	}

	public BmeSupplier getSelectedSupplier() {
		return selectedSupplier;
	}

	public void setSelectedSupplier(BmeSupplier selectedSupplier) {
		this.selectedSupplier = selectedSupplier;
	}

	public List<BmeSaleoutDetail> getSelectedSaleoutDetails() {
		return selectedSaleoutDetails;
	}

	public void setSelectedSaleoutDetails(List<BmeSaleoutDetail> selectedSaleoutDetails) {
		this.selectedSaleoutDetails = selectedSaleoutDetails;
	}

	public List<SelectItem> getItemsStatus() {
		return itemsStatus;
	}

	public void setItemsStatus(List<SelectItem> itemsStatus) {
		this.itemsStatus = itemsStatus;
	}
	
}